<template>
  <el-dialog @close="dialogClose"
             class="map-dialog"
             title="选择经纬度"
             :append-to-body="true"
             :close-on-click-modal='false'
             :visible.sync="visible">
    <div class='map-box'>
      <el-autocomplete style="width:100%;"
                       popper-class="autoAddressClass"
                       v-model="form.address"
                       :fetch-suggestions="querySearchAsync"
                       :trigger-on-focus="true"
                       placeholder="详细地址"
                       @change="querySearchAsync"
                       @select="handleSelect"
                       clearable>
        <template slot-scope="{ item }">
          <i class="el-icon-search fl mgr10"></i>
          <div style="overflow:hidden;">
            <div class="title">{{ item.title }}</div>
            <span class="address ellipsis">{{ item.address }}</span>
          </div>
        </template>
      </el-autocomplete>
      <input type="text"
             style="display:none"
             id="hidden">
    </div>
    <div id="map-container">

    </div>
    <div slot="footer"
         class="dialog-footer">
      <el-button @click="chooseLatLng"
                 type="primary">保 存</el-button>
      <el-button @click="dialogClose">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  data () {
    return {
      visible: false,
      projectInfo: {},
      latLng: {},
      form: {
        address: '', //详细地址
        addrPoint: { //详细地址经纬度
          lng: 0,
          lat: 0
        }
      },
      // 微系统调用时，单独使用变量存储
      latlngData: {
        lat: '',
        lng: ''
      },
      map: '', //地图实例
      mk: '' //Marker实例
    }
  },
  methods: {
    dialogClose () {
      this.$store.dispatch('setChooseLatVisible', false)
      this.$emit('update:dialogVisible', false)
    },
    // 渲染百度地图
    renderMap () {
      this.$nextTick(() => {
        var that = this;
        this.map = new BMap.Map("map-container", { enableMapClick: false })  //新建地图实例，enableMapClick:false ：禁用地图默认点击弹框
        console.log(this.mapLngLat, 'render map')
        // 如果有经纬度，用传入的，没有则使用默认地址
        if (this.mapLngLat.lon && this.mapLngLat.lat) {
          var point = new BMap.Point(this.mapLngLat.lon, this.mapLngLat.lat);
        } else {
          var point = new BMap.Point(120.01612589259, 30.28929432287);
        }

        this.map.centerAndZoom(point, 12)
        this.map.enableScrollWheelZoom()
        this.mk = new BMap.Marker(point, { enableDragging: true }) //创建一个图像标注实例，enableDragging：是否启用拖拽，默认为false
        this.map.addOverlay(this.mk) //将覆盖物添加到地图中
        this.mk.addEventListener('dragend', (e) => {
          let input = document.querySelector('.el-autocomplete input')
          input.blur()
          that.latlngData = {
            lat: e.point.lat,
            lng: e.point.lng
          }
          that.getAddrByPoint(e.point) //拖拽结束后调用逆地址解析函数，e.point为拖拽后的地理坐标
        })
        var navigationControl = new BMap.NavigationControl({ //创建一个特定样式的地图平移缩放控件
          anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
          type: BMAP_NAVIGATION_CONTROL_SMALL //SMALL控件类型
        })
        this.map.addControl(navigationControl) //将控件添加到地图
        var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT }) //创建一个地图定位控件
        geolocationControl.addEventListener("locationSuccess", function (e) { //绑定定位成功后事件
          that.getAddrByPoint(e.point) //定位成功后调用逆地址解析函数
        });
        geolocationControl.addEventListener("locationError", function (e) { //绑定定位失败后事件
          alert(e.message);
        });
        this.map.addControl(geolocationControl) //将控件添加到地图


        // this.geolocation()
        this.map.addEventListener('dragend', (e) => {
          let input = document.querySelector('.el-autocomplete input')
          input.blur()
        })
        this.map.addEventListener('click', (e) => { //给地图绑定点击事件
          // 点击地图时让输入框失去焦点，便于回到输入框时再次触发搜索事件
          let input = document.querySelector('.el-autocomplete input')
          input.blur()
          this.latlngData = {
            lat: e.point.lat,
            lng: e.point.lng
          }

          that.getAddrByPoint(e.point) //点击后调用逆地址解析函数
        })

        // let map = new BMap.Map('map-container')
        // map.centerAndZoom(new BMap.Point(120.01612589259, 30.28929432287), 12)
        // map.enableScrollWheelZoom()
        // map.addEventListener('click', (e) => {
        //   map.clearOverlays()
        //   let point = new BMap.Point(e.point.lng, e.point.lat)
        //   let marker = new BMap.Marker(point)
        //   map.addOverlay(marker)
        //   this.latLng = e.point
        //   console.log(e.point)
        // })
      })
    },
    // 确定选择经纬度
    chooseLatLng () {
      this.$nextTick(() => {
        if (!this.latlngData.lng) {
          this.$message.warning('请点击地图选择具体位置')
          return
        }
        // console.log('this.latlngData', this.latlngData)
        this.projectInfo.lon = this.latlngData.lng
        this.projectInfo.lat = this.latlngData.lat
        this.projectInfo.lonlat = this.projectInfo.lon + '-' + this.projectInfo.lat;
        if (this.currentProBaseInfoComp != 'tab基本信息组件') {
          this.$emit('update:mapLngLat', this.projectInfo)
        } else {//tab基本信息组件
          this.callBackLonlat(this.projectInfo.lonlat, this.projectInfo.lon, this.projectInfo.lat);//经伟度
        }
        this.$emit('update:latlng', this.latlngData)
        this.dialogClose()
      })

    },
    /**
    * 逆地址解析函数（根据坐标点获取详细地址）
    * @param {Object} point   百度地图坐标点，必传
    */
    getAddrByPoint (point) {
      var that = this;
      var geco = new BMap.Geocoder();
      geco.getLocation(point, function (res) {
        console.log('res', res)  //内容见下图
        that.latLng = res.point
        that.mk.setPosition(point) //重新设置标注的地理坐标
        that.map.panTo(point)  //将地图的中心点更改为给定的点
        that.form.address = res.address;  //记录该点的详细地址信息
        that.form.addrPoint = point;  //记录当前坐标点
      })
    },
    /**
   * 浏览器定位函数
   */
    geolocation () {
      var that = this;
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function (res) {
        console.log('point--->', res)
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          that.getAddrByPoint(res.point) //当成功时，调用逆地址解析函数
        } else {
          alert('failed' + this.getStatus()); //失败时，弹出失败状态码
        }
      },
        { enableHighAccuracy: true }) //enableHighAccuracy：是否要求浏览器获取最佳效果，默认为false
    },
    querySearchAsync (str, cb) {
      var options = {
        onSearchComplete: function (res) { //检索完成后的回调函数
          var s = [];
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i));
            }
            cb(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options) //创建LocalSearch构造函数
      local.search(str) //调用search方法，根据检索词str发起检索
    },
    handleSelect (item) {
      this.latlngData.lng = item.point.lng
      this.latlngData.lat = item.point.lat
      this.form.address = item.address + item.title; //记录详细地址，含建筑物名
      this.form.addrPoint = item.point; //记录当前选中地址坐标
      this.map.clearOverlays() //清除地图上所有覆盖物
      this.mk = new BMap.Marker(item.point) //根据所选坐标重新创建Marker
      this.map.addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.map.panTo(item.point) //将地图的中心点更改为选定坐标点
    }
  },
  watch: {
    dialogVisible (newval, oldval) {
      this.visible = newval
      if (this.visible) {
        this.renderMap()
      }
    },
    mapLngLat: {
      handler (newval, oldval) {
        this.projectInfo = JSON.parse(JSON.stringify(newval))
      },
      deep: true
    },
    latlng: {
      handler (newval) {
        let tmp = JSON.parse(JSON.stringify(newval))
        this.latlngData = Object.assign(this.latlngData, tmp)
      },
      deep: true
    }
  },
  props: {
    currentProBaseInfoComp: {
      type: String,
      default: () => {
        return ''
      }
    },
    callBackLonlat: {
      type: Function
    },
    dialogVisible: Boolean,
    mapLngLat: Object,
    latlng: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  created () {

  },
  mounted () {
    setTimeout(() => {

    }, 1000)
  }

}
</script>
<style scoped lang='scss'>
#map-container {
  width: 100%;
  height: 400px;
}
.map-box {
  margin-bottom: 15px;
}
.map-dialog {
  z-index: 3000 !important;
}
.autoAddressClass {
  z-index: 3000;
  li {
    i.el-icon-search {
      margin-top: 11px;
    }
    .mgr10 {
      margin-right: 10px;
    }
    .title {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .address {
      line-height: 1;
      font-size: 12px;
      color: #b4b4b4;
      margin-bottom: 5px;
    }
  }
}
</style>
